package com.seven.z7.logviewer.controls.panel;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

/**
 * 
 * @author aprokofjev
 */

public class ColorJTextPane extends JTextPane {

    private static final String YEAR = Integer.toString(Calendar.getInstance().get(Calendar.YEAR));

    private IColouringAgent mColoringAgent;
    private AttributeSet mAttribute;

    public ColorJTextPane(File file) throws SAXException, ParserConfigurationException, IOException {
        mColoringAgent = new DDMSColouringAgent(file);
    }

    public ColorJTextPane(IColouringAgent agent) {
        mColoringAgent = agent;
    }

    @Override
    public void setText(String line) {
        StringBuilder sb = new StringBuilder(line);
        sb.append("\n");
        setCaretPosition(getDocument().getLength()); // place caret at the end (with no selection)
        if (line.startsWith(YEAR)) {
            mAttribute = mColoringAgent.getAttributeSet(line);
        }
        if (mAttribute != null) {
            setCharacterAttributes(mAttribute, false);
            replaceSelection(sb.toString());
        }
    }
}
